"""
Case Type   : 资源池化集群DMS reform优化
Case Name   : 踢出备机->不执行refrom
Create At   : 2024/05/13
Owner       : @kyleze
Description :
    1.踢出备机
    2.查询集群状态
    3.查看reform线程和startupprocess线程日志
Expect      :
    1.成功
    2.集群恢复正常
    3.不执行refrom
History     :
"""

import os
import unittest
import time

from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH

from yat.test import Node
from yat.test import macro


class DmsRform(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.dirname(__file__)} start----')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH("PrimaryDbUser")
        self.pri_user_node = Node(node="PrimaryDbUser")
        self.st1_user_node = Node(node="Standby1DbUser")
        self.st2_user_node = Node(node="Standby2DbUser")
        self.dms_log_file = os.path.join('$GAUSSLOG', 'pg_log/dn_6001/*.rlog')
        self.reform_start = int(self.st1_user_node.sh(
            f'source {macro.DB_ENV_PATH};'
            f'grep "SS reform/SS switchover/SS failover" '
            f'{self.dms_log_file}|wc -l').result())

    def test_dms(self):
        step = '--step1:踢出备机 expect:成功--'
        self.log.info(step)
        stop_res = self.primary_sh.exec_cm_ctl('stop', '-n 2')
        self.log.info(stop_res)
        self.assertIn(
            self.constant.cm_stop_node_success_msg, stop_res,
            "执行失败" + step)

        step = '--step2:查看集群状态 expect:集群状态正常--'
        self.log.info(step)
        time.sleep(20)
        status = self.primary_sh.get_db_cluster_status('status')
        self.assertTrue("Normal" in status, "执行失败" + step)

        step = '--step3:查看reform线程和startupprocess线程日志 ' \
               'expect:reform线程在startupprocess线程之前'
        self.log.info(step)
        new_reform_start = int(self.st1_user_node.sh(
            f'source {macro.DB_ENV_PATH};'
            f'grep "SS reform/SS switchover/SS failover" '
            f'{self.dms_log_file}|wc -l').result())
        self.assertTrue(new_reform_start == self.reform_start, "执行失败" + step)

    def tearDown(self):
        self.log.info('--恢复环境--')
        start_res = self.primary_sh.exec_cm_ctl('start', '-n 2')
        self.log.info(start_res)
        self.assertIn(
            self.constant.cm_start_node_success_msg, start_res, "恢复环境失败")
        self.log.info(f'----{os.path.dirname(__file__)} end----')
